<template>
	<div style="text-align: center;padding:20px">
		<el-button type="primary" icon="el-icon-calendar" @click="createMeeting" style="float: left;">预约</el-button>
		<div style="float: right;">
			<div style="display: inline-block">
				<div style="display: inline-block;line-height: 20px">已预约：</div>
				<div style="height: 15px;width: 20px;display: inline-block;background: #bd93f9;"></div>
			</div>
			<div style="display: inline-block;margin-left: 20px">
				<div style="display: inline-block;line-height: 20px">预约中：</div>
				<div style="height: 15px;width: 20px;display: inline-block;background: #2F88FF;"></div>
			</div>
		</div>
		<div style="display: inline-flex;margin-right: 20px;">
			<el-button type="success" icon="el-icon-arrow-left-bold" @click="DayReduce" :disabled="reduceBtn"></el-button>
		</div>
		<div style="display: inline-flex;"><span style="font-size: 30px;font-weight: 600;">{{ yearMonthValue }}</span></div>
		<div style="display: inline-flex;margin-left: 20px;">
			<el-button type="success" icon="el-icon-arrow-right-bold" @click="DayAdd"></el-button>
		</div>
	</div>
	<div class="byted-weektime">
		<div class="calendar">
			<table class="calendar-table" style="width:100%">
				<thead class="calendar-head">
				<tr>
					<th rowspan="6" class="week-td">会议室列表</th>
					<th colspan="24">00:00 - 12:00</th>
					<th colspan="24">12:00 - 24:00</th>
				</tr>
				<tr>
					<td colspan="2" v-for="index in tableHeader" :key="index">{{ index }}</td>
				</tr>
				</thead>
				<tbody id="tableBody">
				<div id="kuang" :style="{width:kuangObj.width+'px',height:kuangObj.height+'px',top:kuangObj.top+'px',left:kuangObj.left+'px',bottom:kuangObj.bottom+'px',right:kuangObj.right+'px'}"></div>
				<tr v-for="room in roomList" :key="room.roomId">
					<td>{{ room.name }}</td>
					<td @mousedown.prevent="testCanTest(i,room.roomId) && handleMouseDown(i,room.roomId)"
						@mouseup.prevent="testCanTest(i,room.roomId) && handleMouseUp(i,room.roomId)"
						class="calendar-atom-time" :class="item.class"
						v-for="(item,i) in rowUnit[room.roomId]" :key="i"></td>
				</tr>
				<tr>
					<td colspan="49" class="td-table-tip">
						<div class="clearfix">
							<span class="pull-left tip-text">请用鼠标滑动选择时间段进行预约会议</span>
						</div>
					</td>
				</tr>
				<tr>
					<td colspan="49" class="timeContent" style="text-align: left;padding: 20px;">
						<div v-for="item in roomList" :key="item.roomId">
							<span>{{ item.name }}: </span>
							<strong><span>{{ timeStr[item.roomId] }}</span></strong>
						</div>
					</td>
				</tr>
				</tbody>
			</table>
		</div>
	</div>
	<scTable ref="table" :data="dayMeetingList" row-key="meetingId" stripe>
		<el-table-column label="#" type="index" width="50"></el-table-column>
		<el-table-column label="会议类型" prop="meetingTypeName" width="100"></el-table-column>
		<el-table-column label="会议主题" prop="subject" width="250" :show-overflow-tooltip="true"></el-table-column>
		<el-table-column label="预约状态" prop="sex" width="100">
			<template #default="scope">
				<el-tag v-if="scope.row.status=='0'">预约中</el-tag>
				<el-tag v-if="scope.row.status=='1'" type="success">已占用</el-tag>
			</template>
		</el-table-column>
		<el-table-column label="开始时间" prop="beginTime" width="150"></el-table-column>
		<el-table-column label="结束时间" prop="endTime" width="150"></el-table-column>
		<el-table-column label="联系电话" prop="tel" width="150"></el-table-column>
		<el-table-column label="操作" fixed="right" align="right" width="170">
			<template #default="scope">
				<el-button-group v-if="scope.row.isMe=='1'">
					<el-button text type="primary" size="small" @click="table_edit(scope.row, scope.$index)">编辑</el-button>
					<el-popconfirm title="确定删除吗？" @confirm="table_del(scope.row, scope.$index)">
						<template #reference>
							<el-button text type="primary" size="small">删除</el-button>
						</template>
					</el-popconfirm>
				</el-button-group>
			</template>
		</el-table-column>
	</scTable>

	<save-dialog v-if="dialog.save" ref="saveDialog" @success="handleSaveSuccess" @closed="dialog.save=false"></save-dialog>
</template>

<script>

import saveDialog from "./save";

export default {
	name: 'Apply Meeting',
	components: {saveDialog},
	data() {
		return {
			dayMeetingList: [],
			dialog: {
				save: false
			},
			reduceBtn: true,
			yearMonthValue: "",
			roomList: [],
			tableHeader: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'],
			rowUnit: {},
			timeContent: [ //选中的时间段原始数据
			],
			timeSection: [  //时间段,可以返回给后端的数据
			],
			timeStr: [],
			roomId: '',
			beginTime: 0,
			downEvent: false,
			kuangObj: {
				width: 0,
				height: 0,
				top: 0,
				left: 0,
				bottom: 0,
				right: 0,
				oldLeft: 0,
				oldTop: 0,
				flag: false
			}
		}
	},
	created() {
		this.getNowDay();
		this.init()
	},
	mounted() {

	},
	methods: {
		async getMeetingListByDayStr() {
			var res = await this.$API.office.meeting.getMeetingListByDayStr.get({dayStr: this.yearMonthValue});
			if (res.code == 200) {
				this.dayMeetingList = res.data;
			}
		},
		getNowDay() {
			let year = new Date().getFullYear();
			let month = new Date().getMonth() + 1;
			let day = new Date().getDate();
			if(month<10)
			{
				month="0"+month;
			}
			if(day<10)
			{
				day="0"+day;
			}
			this.yearMonthValue = year + "-" + month + "-" + day;
		},
		async init() {
			var res = await this.$API.office.meeting.getMeetingByDay.get({dayStr: this.yearMonthValue});
			if (res.code == 200) {
				this.roomList = res.data;
				this.roomList.forEach(item => {
					let arr = []
					for (let j = 0; j < 48; j++) {
						arr.push({class: null, timeData: j})
					}
					this.rowUnit[item.roomId] = arr
					this.timeContent[item.roomId] = {arr: []}
					this.timeSection[item.roomId] = [];
					this.timeStr[item.roomId] = '';
					let meetingList = item.meetingList;
					meetingList.forEach(meeting => {
						let start = meeting.meetingBegin;
						let end = meeting.meetingEnd;
						for (let y = start; y < end + 1; y++) {
							if (this.rowUnit[item.roomId][y].class == null) {
								if (meeting.status == "1") {
									this.rowUnit[item.roomId][y].class = 'ui-cannot-selected'
								} else {
									this.rowUnit[item.roomId][y].class = 'ui-selected'
								}
								this.timeContent[item.roomId].arr.push(this.rowUnit[item.roomId][y].timeData)
							}
						}
					})
					this.filterTime(item.roomId)
				})
			}
			this.getMeetingListByDayStr();
		},
		testCanTest(i, roomId) {
			if (this.timeContent[roomId].arr.includes(i)) {
				if (this.rowUnit[roomId][i].class == "ui-selected") {
					return true
				} else {
					this.$alert("该时间段已被他人预定！", "提示", {type: 'error'})
					return false;
				}
			} else {
				return true;
			}
		},
		handleMouseDown(i, roomId) {
			this.downEvent = true //按下时鼠标不在范围内则不算
			this.roomId = roomId
			this.beginTime = i
		},
		handleMouseUp(i, roomId) {
			//当点击事件是在table内才触发选取数据操作
			if (this.downEvent) {
				//选时间段
				let _this = this
				let begin = this.beginTime
				let start = begin <= i ? begin : i //x轴 起点
				let length = Math.abs(begin - i)
				let end = start + length           //x轴 终点
				let flag = false;
				//当框选范围内所有块都是选中状态时,执行反选
				for (let y = start; y < end + 1; y++) {
					if (_this.rowUnit[roomId][y].class == null) {
						flag = true
					}
				}
				if (flag) {
					for (let y = start; y < end + 1; y++) {
						if (this.rowUnit[roomId][y].class == null) {
							this.rowUnit[roomId][y].class = 'ui-selected'
							this.timeContent[roomId].arr.push(this.rowUnit[roomId][y].timeData)
						}
					}
				} else { //反选
					for (let y = start; y < end + 1; y++) {
						this.rowUnit[roomId][y].class = null
						let index = this.timeContent[roomId].arr.findIndex(item => item == this.rowUnit[roomId][y].timeData)
						this.timeContent[roomId].arr.splice(index, 1)
					}
				}
				//过滤时间段,将临近的时间段合并
				this.filterTime(roomId)
				this.downEvent = false
				if (flag) {
					var params = {
						roomId: roomId,
						beginTime: this.yearMonthValue + " " + this.toStr(start / 2),
						endTime: this.yearMonthValue + " " + this.toStr(end / 2 + 0.5)
					};
					this.dialog.save = true
					this.$nextTick(() => {
						this.$refs.saveDialog.open().setCreateData(params, this.roomList)
					})
				}
			}
		},
		createMeeting() {
			this.dialog.save = true
			this.$nextTick(() => {
				this.$refs.saveDialog.open();
			})
		},
		table_edit(row, index) {
			this.dialog.save = true
			this.$nextTick(() => {
				this.$refs.saveDialog.open("edit").setData(row,this.roomList);
			})
		},
		async table_del(row) {
			var reqData = {meetingId: row.meetingId}
			var res = await this.$API.office.meeting.deleteMeeting.post(reqData);
			if (res.code == 200) {
				this.init();
				this.$message.success("删除成功")
			} else {
				this.$alert(res.message, "提示", {type: 'error'})
			}
		},

		filterTime(roomId) {  //选中的x,y坐标信息 x:0-47  y:0-6
			function sortCut(arr) {  //提取连续的数字
				var result = []
				arr.forEach(function (v, i) {
					var temp = result[result.length - 1];
					if (!i) {
						result.push([v]);
					} else if (v % 1 === 0 && v - temp[temp.length - 1] == 1) {
						temp.push(v)
					} else {
						result.push([v])
					}
				});
				return result
			}

			//排序,分割成
			let arr1 = sortCut(this.timeContent[roomId].arr.sort((a, b) => a - b))
			let arr2 = []
			arr1.forEach((arr) => {   //转成带小数点的时间段,以及供前端显示的字符串
				let arr3 = []
				arr3.push(arr[0] / 2)
				arr3.push(arr[arr.length - 1] / 2 + 0.5)
				arr2.push(arr3)
			})
			this.timeStr[roomId] = this.timeToStr(arr2)
			this.timeSection[roomId] = arr2
		},
		clearDragData() {
			for (let prop in this.kuangObj) {
				this.kuangObj[prop] = 0
			}
		},
		DayAdd() {
			let currentDate = this.yearMonthValue;
			currentDate = new Date(currentDate);
			let nextDate = currentDate.setMonth(currentDate.getMonth()); // 输出日期格式为毫秒形式1556668800000
			nextDate = new Date(nextDate);
			let nextYear = nextDate.getFullYear();
			let nextMonth = this.checkMonth(nextDate.getMonth() + 1); // 因日期中的月份表示为0-11，所以要显示正确的月份，需要 + 1
			let nextDay = currentDate.setDate(currentDate.getDate() + 1); // 输出日期格式为毫秒形式1556668800000
			nextDay = new Date(nextDay);
			let nextday = nextDay.getDate()
			if(nextday<10)
			{
				nextday="0"+nextday;
			}
			nextDate = nextYear + "-" + nextMonth + "-" + nextday; // "2019-05"
			this.yearMonthValue = nextDate;
			this.reduceBtn = false;
			this.init();
			this.getMeetingListByDayStr();
		},
		DayReduce() {
			let currentDate = this.yearMonthValue;
			currentDate = new Date(currentDate);
			let nextDate = currentDate.setMonth(currentDate.getMonth()); // 输出日期格式为毫秒形式1556668800000
			nextDate = new Date(nextDate);
			let nextYear = nextDate.getFullYear();
			let nextMonth = this.checkMonth(nextDate.getMonth() + 1); // 因日期中的月份表示为0-11，所以要显示正确的月份，需要 + 1
			let nextDay = currentDate.setDate(currentDate.getDate() - 1); // 输出日期格式为毫秒形式1556668800000
			nextDay = new Date(nextDay);
			let nextday = nextDay.getDate();
			if(nextday<10)
			{
				nextday="0"+nextday;
			}
			nextDate = nextYear + "-" + nextMonth + "-" + nextday; // "2019-05"
			this.yearMonthValue = nextDate;
			let year = new Date().getFullYear();
			let month = new Date().getMonth() + 1;
			let day = new Date().getDate();
			if(month<10)
			{
				month="0"+month;
			}
			if(day<10)
			{
				day="0"+day;
			}
			let nowTime = year + "-" + month + "-" + day;
			if (nowTime == this.yearMonthValue) {
				this.reduceBtn = true;
			}
			this.init();
			this.getMeetingListByDayStr();
		},
		checkMonth(i) {
			if (i < 10) {
				i = "0" + i;
			}
			return i;
		},
		timeToStr(arr) {  //把数组转成方便人看到字符串
			let str = ''
			arr.forEach((arr, index) => {
				let str1 = ''
				if (index == 0) {
					str1 = this.toStr(arr[0]) + '~' + this.toStr(arr[1])
				} else {
					str1 = ' , ' + this.toStr(arr[0]) + '~' + this.toStr(arr[1])
				}
				str += str1
			})
			return str
		},
		toStr(num) {
			if (Number.isInteger(num)) {
				let str = num < 10 ? ('0' + num) : num.toString()
				return str + ':00'
			} else {
				let str = Math.floor(num) < 10 ? ('0' + Math.floor(num)) : Math.floor(num).toString()
				return str + ':30'
			}
		},
		//本地更新数据
		handleSaveSuccess() {
			this.init();
		}
	}
}
</script>

<style scoped>
.byted-weektime .calendar {
	-webkit-user-select: none;
	position: relative;
}

.byted-weektime .calendar .calendar-table {
	border-collapse: collapse;
	border-radius: 4px
}

.byted-weektime .calendar .calendar-table tr .calendar-atom-time:hover {
	background: #ccc
}

.byted-weektime .calendar .calendar-table tr .ui-selected {
	background: #2F88FF
}

.byted-weektime .calendar .calendar-table tr .ui-cannot-selected {
	background: #bd93f9
}

.byted-weektime .calendar .calendar-table tr .ui-selected:hover {
	background: #2F88FF
}

.byted-weektime .calendar .calendar-table tr, .byted-weektime .calendar .calendar-table td, .byted-weektime .calendar .calendar-table th {
	border: 1px solid #ccc;
	font-size: 12px;
	text-align: center;
	min-width: 11px;
	line-height: 1.8em;
	-webkit-transition: background 200ms ease;
	-moz-transition: background 200ms ease;
	-ms-transition: background 200ms ease;
	transition: background 200ms ease
}

.byted-weektime .calendar .calendar-table tbody tr {
	height: 50px
}

.byted-weektime .calendar .calendar-table tbody tr td:first-child {
	background: #F8F9FA
}

.byted-weektime .calendar .calendar-table thead th, .byted-weektime .calendar .calendar-table thead td {
	background: #F8F9FA
}

.byted-weektime .calendar .calendar-table .td-table-tip {
	line-height: 2.4em;
	padding: 0 12px 0 19px;
	background: #fff !important
}

.byted-weektime .calendar .calendar-table .td-table-tip .clearfix {
	height: 46px;
	line-height: 46px
}

.byted-weektime .calendar .calendar-table .td-table-tip .pull-left {
	font-size: 14px;
	color: #333333
}

.byted-weektime .week-td {
	width: 75px;
	padding: 20px 0
}

.byted-weektime a {
	cursor: pointer;
	color: #2F88FF;
	font-size: 14px
}

#kuang {
	position: absolute;
	background-color: blue;
	opacity: 0.3;
}
</style>

